package logic

import (
	"context"
	"encoding/json"
	"xialou_platform/app/constx"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/tools"
	"xialou_platform/services/system/rpc/systemClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaleCardMiniCodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSaleCardMiniCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaleCardMiniCodeLogic {
	return &SaleCardMiniCodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SaleCardMiniCodeLogic) SaleCardMiniCode(req *types.SaleCardMiniCodeReq) (resp *types.SaleCardMiniCodeResp, err error) {

	reqStr, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}
	sysConfig, err := l.svcCtx.SystemRpc.SysConfigByKey(l.ctx, &systemClient.KeyReq{Key: constx.MiniCodeApi})
	if err != nil {
		return nil, err
	}

	agentId, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return nil, err
	}
	bytes, err := tools.RequestOtherPlatform(
		sysConfig.ConfigValue,
		"POST",
		l.svcCtx.Config.Auth.AccessSecret,
		string(reqStr),
		l.svcCtx.Config.Auth.AccessExpire,
		agentId, // admin_users表 下楼系统账户的ID
	)
	if err != nil {
		return nil, err
	}

	var res tools.CommonResp[types.SaleCardMiniCodeResp]
	err = json.Unmarshal(bytes, &res)
	if err != nil {
		logx.Infof("调用%v获取小程序码接口err：%v", "xiuxian", err.Error())
		return nil, errorx.NewMsgReasonCodeError(errorx.DefaultCode, "调用获取小程序码口err：%v", err.Error())
	}

	logx.Infof("获取小程序码: %v", res)
	if res.Code != 200 {
		return nil, errorx.NewCodeReason(res.Code, res.Message)
	}

	resp = &types.SaleCardMiniCodeResp{
		QrCodeUrl: res.Data.QrCodeUrl,
	}
	return
}
